<template>
  <div>
    <el-button type="primary" @click="tan('添加')">添加角色</el-button>
    <div class="bg">
      <el-table :data="shuju.object" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="props" tree-props>
            <!-- 权限级别  一共24格-->
            <el-row
              :class="['bgbuttom']"
              v-for="(item1, i1) in props.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染  占5格-->
              <el-col :span="5">
                <el-tag closable @close="open(props.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <el-icon><CaretRight /></el-icon>
              </el-col>
              <!-- 二级和三级权限渲染 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级去权限 -->
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="open(props.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <el-icon><CaretRight /></el-icon>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="open(props.row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ props.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 表头部分 -->
        <el-table-column label="角色id" prop="id" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="角色描述" prop="roleDesc" />
        <el-table-column label="操作" width="300">
          <template #default="scope" v-slot="{ row }">
            <div style="display: flex; align-items: center">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="tan('编辑', scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="open(scope.row)"
                >删除</el-button
              >
              <el-button
                type="warning"
                size="small"
                :icon="Edit"
                @click="tan('分配', scope.row)"
                >分配权限</el-button
              >
            </div>
          </template> </el-table-column
        >>
      </el-table>
    </div>
    <!-- 弹出面板 -->
    <div class="showtime">
      <el-dialog
        v-model="dialogVisible"
        title="编辑角色"
        width="50%"
        :before-close="handleClose"
        @close="jiangting"
      >
        <div v-if="tcys == 2">
          <!-- 树型框 -->
          <el-tree
            :data="tree.object"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="defkeys"
            ref="treeRef"
            @node-click="handleNodeClick"
          />
        </div>
        <div v-else>
          <el-form
            ref="formRef"
            :label-position="labelPosition"
            label-width="100px"
            :model="formLabelAlign"
            style="max-width: 460px"
            :rules="rules"
          >
            <el-form-item v-if="tcys == 0" label="角色名称" prop="name">
              <el-input v-model="formLabelAlign.name" />
            </el-form-item>
            <el-form-item v-else label="角色名称">
              <el-input v-model="formLabelAlign.name" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="formLabelAlign.region" />
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button v-if="tcys == 2" type="primary" @click="shuxing"
              >确定</el-button
            >
            <el-button v-else type="primary" @click="submitForm(formRef)"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch, getCurrentInstance } from 'vue';
import { Edit, Setting, Delete, Search } from '@element-plus/icons-vue';
import { apis } from '@/http/api';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import type { Action } from 'element-plus';
import { ElTree } from 'element-plus';
import type Node from 'element-plus/es/components/tree/src/model/node';
const treeRef = ref<InstanceType<typeof ElTree>>();
interface Tree {
  label: string;
  children?: Tree[];
}

const formRef = ref<FormInstance>();
const dialogVisible = ref(false);
const shuju = reactive({
  object: null as any, //表单内容
});
const defkeys = ref([]) as any;
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('你确定关闭吗?')
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
//表单
const labelPosition = ref('right');
const formLabelAlign = reactive({
  id: 0, //id
  name: '', //名称
  region: '', //描述
});
//验证规则
const rules = ref({
  name: [
    { required: true, message: '请填写名称', trigger: 'blur' },
    { type: 'string', message: '长度为3~5', trigger: 'blur' },
  ],
});
//获取数据
const huoqu = () => {
  apis.getguanli().then(({ data }) => {
    shuju.object = data;
    console.log(shuju.object);
  });
};
//获取树状图数据
const tree = reactive({
  object: null as any,
});
//删除提示
const open = (val: any, id?: number) => {
  ElMessageBox.confirm('你确定要删除吗?', '提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
      if (id !== undefined) {
        apis.delquanxian(val.id, id).then((data) => {
          if (data.meta.status !== 200) {
            console.log('删除失败');
          } else {
            console.log('删除成功');
            val.children = data.data;
          }
        });
      } else {
        apis.deljuese(val.id).then((data) => {
          if (data.meta.status !== 200) {
            console.log('删除失败');
          } else {
            console.log('删除成功');
            huoqu();
          }
        });
      }
    })
    .catch((action: Action) => {
      ElMessage({
        type: 'info',
        message: action === 'cancel' ? '取消成功' : '已取消',
      });
    });
};
//弹出框样式
const tcys = ref(0);
//弹出框
const tan = (val: string, value?: any) => {
  dialogVisible.value = true;

  if (value !== undefined) {
    var a = JSON.parse(JSON.stringify(value));
  }
  switch (val) {
    case '添加':
      tcys.value = 0;
      break;
    case '编辑':
      tcys.value = 1;
      formLabelAlign.id = a.id;
      formLabelAlign.name = a.roleName;
      formLabelAlign.region = a.roleDesc;
      break;
    case '分配':
      tcys.value = 2;
      formLabelAlign.id = a.id;
      apis.getquanxian('tree').then((res) => {
        if (res.meta.status !== 200) {
          console.log('获取失败');
        } else {
          tree.object = res.data;

          getkeys(value, defkeys.value);
        }
      });

      break;

    default:
      break;
  }
};

//确认
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      dialogVisible.value = false;
      switch (tcys.value) {
        case 0:
          apis.postjuese(formLabelAlign.name, formLabelAlign.region);

          break;
        case 1:
          apis.putjuese(
            formLabelAlign.id,
            formLabelAlign.name,
            formLabelAlign.region
          );
          break;
        default:
          break;
      }
      huoqu();
    } else {
      return false;
    }
  });
};
//树状图
const handleNodeClick = (data: Tree) => {
  console.log(data);
};
const defaultProps = {
  children: 'children', //子组件
  label: 'authName', //名字
};
const shuxing = () => {
  let keys = [];
  const ids = [] as any;
  keys = treeRef.value!.getCheckedNodes(false, false); //函数第一个是节点值,false不能修改, 要不然会自己默认刷新为空,踏马的,凸(艹皿艹 )
  //  后面的是data,具体不知道
  console.log('数据', keys);

  keys.forEach((item) => {
    ids.push(item.id);
  });
  const val = ids.join(','); //权限id转换为字符串
  console.log(val);

  apis.postshouquan(formLabelAlign.id, val).then((data) => {
    if (data.meta.status !== 200) {
      console.log('获取失败');
    } else {
      //获取成功
      console.log('获取成功', data);
      huoqu();
    }
  });
  // apis.postshouquan();
  // huoqu();
  dialogVisible.value = false;
};
//通过递归的形式,获取角色下所有的三级权限的id,并保存到defkeys中
const getkeys = (node: any, arr: any) => {
  if (!node.children) {
    return arr.push(node.id);
  }
  //递归
  node.children.forEach((item: any) => {
    getkeys(item, arr);
  });
};
//监听分配权限
const jiangting = () => {
  defkeys.value = [];
};

//渲染数据
onMounted(() => {
  huoqu();
});
//监听事件
watch(dialogVisible, (newName, oldName) => {
  if (newName == false) {
    formLabelAlign.name = '';
    formLabelAlign.region = '';
  }
});
</script>

<style lang="less" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
.el-tag {
  margin: 10px;
  height: 40px;
  line-height: 40px;
}
.bgtop {
  border: 1px solid #eee;
}
.bgbuttom {
  border: 1px solid #eee;
}
</style>
